package com.example.cemenghuii.controller;

import com.example.cemenghuii.dto.ApiResponse;
import com.example.cemenghuii.entity.Course;
import com.example.cemenghuii.entity.User;
import com.example.cemenghuii.service.CourseService;
import com.example.cemenghuii.service.UserService;
import com.example.cemenghuii.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/course")
@CrossOrigin(origins = "*")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 创建课程
     */
    @PostMapping
    public ApiResponse<Void> createCourse(@RequestHeader("Authorization") String token,
                                          @RequestBody Course course) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            User user = userService.getUserById(userId);
            if (user == null) {
                return ApiResponse.unauthorized("用户不存在");
            }

            course.setPublisherId(userId);
            course.setPublisherName(user.getUsername());

            boolean success = courseService.createCourse(course);
            if (success) {
                if (userType == 2) {
                    return ApiResponse.success("课程发布成功");
                } else {
                    return ApiResponse.success("课程提交成功，等待审核");
                }
            } else {
                return ApiResponse.error("课程创建失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新课程
     */
    @PutMapping("/{id}")
    public ApiResponse<Void> updateCourse(@RequestHeader("Authorization") String token,
                                          @PathVariable Long id,
                                          @RequestBody Course course) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!courseService.checkCoursePermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此课程");
            }

            course.setId(id);
            // 企业用户修改后需要重新审核
            if (userType == 1) {
                course.setStatus(0); // 重新设为待审核
            }

            boolean success = courseService.updateCourse(course);
            if (success) {
                return ApiResponse.success("课程更新成功");
            } else {
                return ApiResponse.error("课程更新失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除课程
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteCourse(@RequestHeader("Authorization") String token,
                                          @PathVariable Long id) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!courseService.checkCoursePermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此课程");
            }

            boolean success = courseService.deleteCourse(id);
            if (success) {
                return ApiResponse.success("课程删除成功");
            } else {
                return ApiResponse.error("课程删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取课程详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Course> getCourseDetail(@PathVariable Long id,
                                               @RequestParam(defaultValue = "true") Boolean incrementView) {
        try {
            Course course = courseService.getCourseDetail(id, incrementView);
            if (course == null) {
                return ApiResponse.notFound("课程不存在");
            }
            return ApiResponse.success(course);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取课程列表
     */
    @GetMapping("/list")
    public ApiResponse<Map<String, Object>> getCourseList(@RequestHeader("Authorization") String token,
                                                          @RequestParam(required = false) String courseName,
                                                          @RequestParam(required = false) String author,
                                                          @RequestParam(required = false) Integer status,
                                                          @RequestParam(defaultValue = "1") Integer page,
                                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            Long publisherId = null;
            // 企业用户只能查看自己的课程
            if (userType == 1) {
                publisherId = userId;
            }

            Map<String, Object> result = courseService.getCourseList(courseName, author, status, publisherId, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取我的课程列表
     */
    @GetMapping("/my")
    public ApiResponse<Map<String, Object>> getMyCourseList(@RequestHeader("Authorization") String token,
                                                            @RequestParam(defaultValue = "1") Integer page,
                                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            Map<String, Object> result = courseService.getCourseByPublisherId(userId, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 审核课程（管理员功能）
     */
    @PutMapping("/{id}/audit")
    public ApiResponse<Void> auditCourse(@RequestHeader("Authorization") String token,
                                         @PathVariable Long id,
                                         @RequestBody Map<String, Integer> auditData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Integer status = auditData.get("status");
            boolean success = courseService.auditCourse(id, status);
            if (success) {
                String message = status == 1 ? "审核通过" : "审核拒绝";
                return ApiResponse.success(message);
            } else {
                return ApiResponse.error("审核失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 批量审核课程（管理员功能）
     */
    @PutMapping("/batch-audit")
    public ApiResponse<Void> batchAuditCourses(@RequestHeader("Authorization") String token,
                                               @RequestBody Map<String, Object> auditData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            @SuppressWarnings("unchecked")
            List<Long> courseIds = (List<Long>) auditData.get("courseIds");
            Integer status = (Integer) auditData.get("status");

            boolean success = courseService.batchAuditCourses(courseIds, status);
            if (success) {
                String message = status == 1 ? "批量审核通过" : "批量审核拒绝";
                return ApiResponse.success(message);
            } else {
                return ApiResponse.error("批量审核失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取待审核课程列表（管理员功能）
     */
    @GetMapping("/pending")
    public ApiResponse<Map<String, Object>> getPendingCourseList(@RequestHeader("Authorization") String token,
                                                                 @RequestParam(defaultValue = "1") Integer page,
                                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);

            // 检查是否为超级管理员
            if (!userService.isSuperAdmin(userId)) {
                return ApiResponse.forbidden("权限不足");
            }

            Map<String, Object> result = courseService.getPendingCourseList(page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取已发布课程列表（小程序端）
     */
    @GetMapping("/published")
    public ApiResponse<Map<String, Object>> getPublishedCourseList(@RequestParam(required = false) String keyword,
                                                                   @RequestParam(defaultValue = "1") Integer page,
                                                                   @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = courseService.getPublishedCourseList(keyword, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据排序查询课程
     */
    @GetMapping("/sort/{sortOrder}")
    public ApiResponse<Map<String, Object>> getCoursesBySortOrder(@PathVariable Integer sortOrder,
                                                                  @RequestParam(defaultValue = "1") Integer page,
                                                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = courseService.getCoursesBySortOrder(sortOrder, page, pageSize);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新课程排序
     */
    @PutMapping("/{id}/sort")
    public ApiResponse<Void> updateSortOrder(@RequestHeader("Authorization") String token,
                                             @PathVariable Long id,
                                             @RequestBody Map<String, Integer> sortData) {
        try {
            String jwt = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwt);
            Integer userType = jwtUtil.getUserTypeFromToken(jwt);

            // 检查权限
            if (!courseService.checkCoursePermission(id, userId, userType)) {
                return ApiResponse.forbidden("无权限操作此课程");
            }

            Integer sortOrder = sortData.get("sortOrder");
            boolean success = courseService.updateSortOrder(id, sortOrder);
            if (success) {
                return ApiResponse.success("排序更新成功");
            } else {
                return ApiResponse.error("排序更新失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}